package com.senior.english.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.senior.english.config.LoadConfiguration;
import com.senior.english.model.UserModel;
import com.senior.english.servicesImp.UserService;

@Controller
public class UserController {
	UserService userService = (UserService) LoadConfiguration.loadJDBC()
			.getBean("userDAO");

	@RequestMapping(value = "/userlist", method = RequestMethod.GET)
	public String getUsers(ModelMap model) {
		model.addAttribute("listUser", userService.listUser());
		return "userlist";
	}

	@RequestMapping(value = "/updateuser", method = RequestMethod.GET)
	public String updateUsers(ModelMap model) {
		model.addAttribute("listUser", userService.listUser());
		return "updateuser";
	}

	@RequestMapping(value = "/UP/{i}", method = RequestMethod.GET)
	public String updateUser(ModelMap model,
			@PathVariable(value = "i") Integer i) {
		// UserModel usermodel = new UserModel();
		// model.addAttribute("upUser", userService.getUserById(i));
		model.addAttribute("upUser", userService.getUserById(i));
		return "UP";
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String processUpdateUser(
			@Valid @ModelAttribute("upUser") UserModel usermodel,
			BindingResult result, ModelMap model) {
		userService.updateUser(usermodel.getUser_id(),
				usermodel.getUser_name(), usermodel.getPassword());
		model.addAttribute("upUser", usermodel);
		return "redirect:/userlist";
	}
}
